<?php
/**
 * Created by PhpStorm.
 * User: xding
 * Date: 15-10-13
 * Time: 下午2:06
 */

class Post extends MY_Controller {

    /**
     * @param int $start   query start rows
     */
    public function index($start = 0) {

        $this->output->enable_profiler(TRUE);

        $this->load->model('posts_model','posts');

        // condition params handler
        $conditions   = NULL;
        $post_status  = $this->input->get('post_status');

        empty($post_status) ?: $conditions['post_status'] = $post_status;
        $this->posts->set_query_condition($conditions,\Beans\Post::$_TB_NAME);

        //dump($conditions);

        // create pagination
        $this->load->library('pagination');
        $config['base_url']   = base_url('post/index');
        $config['total_rows'] = $this->posts->get_post_count();
        $config['per_page']   = $this->rows_num;
        $this->pagination->initialize($config);


        $data['page']  = $this->pagination->create_links();
        $data['posts'] = $this->posts->get_post_list($start,$this->rows_num);
        $data['post_status'] = $post_status;

        $this->load->view('post/index',$data);
    }


    public function post_new() {

        if (IS_POST || IS_AJAX)
        {
            // do save post action

            $this->load->library('form_validation');
            $config = array(
                array(
                    'field' => 'postTitle',
                    'label' => '文章标题',
                    'rules' => 'required',
                    'errors' => array(
                        'required' => '%s 不能为空.',
                    ),
                ),
            );

            $this->form_validation->set_rules($config);
            if ( FALSE  === $this->form_validation->run() )
            {
                ajax_return(self::HTTP_STATUS_FAIL,strip_tags(validation_errors()));
            }

            $post = new \Beans\Post();
            $post->post_title    = $this->input->post('postTitle');
            $post->post_content  = $this->input->post('postContent');
            $post->post_excerpt  = $this->input->post('postExcerpt');
            $post->post_author   = $this->input->post('postAuthor');
            $post->post_name     = $this->input->post('postName');
            $post->guid          = $this->input->post('guid');

            $post->post_date     = $this->input->post('postDate');
            empty($post->post_date) && $post->post_date = date('Y-m-d H:i:s');
            $post->post_date_gmt = gmdate("Y-m-d H:i:s",strtotime($post->post_date));
            // post default status is publish
            $post->post_status = $this->input->post('postStatus') ?: 'publish';
            // ping status
            $post->ping_status = $this->input->post('pingStatus') ?: 'public';
            if ( $post->ping_status === \Beans\Post::$PING_STATUS_PASSWORD )
            {
                $post->post_password = $this->input->post('postPassword') ?: '1234';
            }

            $this->load->model('posts_model','posts');
            if ( ! ($post = $this->posts->insert_post($post)) )
            {
                ajax_return(self::HTTP_STATUS_FAIL,'发布文章失败');
            }

            // 更新relationship
            $relationship_obj_arr = array();

            // 默认填充到未分类目录中
            $categorys = $this->input->post('categorys') ?: array(0=>1);
            foreach ( $categorys as $c )
            {
                $rela = new \Beans\Relationship();
                $rela->object_id   = $post->ID;
                $rela->relation_id = intval($c);
                $rela->type        = 'category';

                array_push($relationship_obj_arr,$rela);
            }

            $tags = $this->input->post('tags');
            if ( $tags && is_array($tags) )
            {
                foreach ( $tags as $t )
                {
                    $rela = new \Beans\Relationship();
                    $rela->object_id   = $post->ID;
                    $rela->relation_id = intval($t);
                    $rela->type        = 'tag';

                    array_push($relationship_obj_arr,$rela);
                }
            }

            $this->load->model('relationships_model','relationships');
            if ( FALSE === $this->relationships->insert_relationship($relationship_obj_arr) )
            {
                // 更新relationship失败的时候，文章也将被删除
                $this->posts->delete_post($post->ID);
                ajax_return(self::HTTP_STATUS_FAIL,'更新relationship失败');
            }

            // execute successful
            ajax_return(self::HTTP_STATUS_SUCCESS,'执行成功');
        }
        else
        {
            // show new post page
            $this->load->model('categorys_model','categorys');
            $data['category_arr'] = $this->categorys->handler()->get_category();

            $this->load->model('tags_model','tags');
            $data['tag_arr'] = $this->tags->get_tags();

            $data['post_date'] = date('Y-m-d H:i:s');

            $this->load->view('post/new',$data);
        }
    }


    public function post_del() {

        $ids_string = $this->input->post('ids');

        if ( empty($ids_string) )
        {
            show_error('请传入要删除的文章的ID');
        }

        $this->load->model('posts_model','posts');
        $this->posts->trans_start();
        if ( FALSE !== $this->posts->delete_post($ids_string) )
        {
            // 删除relationship相关数据
            $this->load->model('relationships_model','relationships');
            $res = $this->relationships
                        ->delete_relationship(
                             array(
                                 array(
                                   'key'=>'object_id' ,
                                   'value' => hashids_decode_set($ids_string),
                                   'method' => 'where_in'
                                 )
                             )
                        );

            if ( $res )
            {
                $this->posts->trans_commit();
                ajax_return(self::HTTP_STATUS_SUCCESS,'删除成功');
            }
            $this->posts->trans_rollback()->trans_off();
        }

        ajax_return(self::HTTP_STATUS_FAIL,'删除失败');
    }

    /**
     * 编辑文章
     */
    public function post_edit() {

        if ( IS_POST || IS_AJAX )
        {
            // do save post action
            $this->load->library('form_validation');
            $config = array(
                array(
                    'field' => 'postTitle',
                    'label' => '文章标题',
                    'rules' => 'required',
                    'errors' => array(
                        'required' => '%s 不能为空.',
                    ),
                ),
            );

            $this->form_validation->set_rules($config);
            if ( FALSE  === $this->form_validation->run() )
            {
                ajax_return(self::HTTP_STATUS_FAIL,strip_tags(validation_errors()));
            }

            $post = new \Beans\Post();

            $post->ID            = $this->input->post('id',FALSE);
            if ( !$post->ID )
            {
                show_404('内容不存在');
            }

            $post->ID            = hashids_decode($post->ID);
            $post->post_title    = $this->input->post('postTitle');
            $post->post_content  = $this->input->post('postContent');
            $post->post_excerpt  = $this->input->post('postExcerpt');
            $post->post_author   = $this->input->post('postAuthor');
            $post->post_name     = $this->input->post('postName');
            $post->guid          = $this->input->post('guid');

            // 文章发布时间
            $post->post_date     = $this->input->post('postDate');
            empty($post->post_date) && $post->post_date = date('Y-m-d H:i:s');
            $post->post_date_gmt = gmdate("Y-m-d H:i:s",strtotime($post->post_date));

            // 文章修改时间
            $post->post_modified = date('Y-m-d H:i:s');
            $post->post_modified_gmt = gmdate("Y-m-d H:i:s",strtotime($post->post_modified));

            // post default status is publish
            $post->post_status = $this->input->post('postStatus') ?: 'publish';
            // ping status
            $post->ping_status = $this->input->post('pingStatus') ?: 'public';
            if ( $post->ping_status === \Beans\Post::$PING_STATUS_PASSWORD )
            {
                $post->post_password = $this->input->post('postPassword') ?: '1234';
            }

            $this->load->model('posts_model','posts');
            if ( ! ($post = $this->posts->update_post($post)) )
            {
                ajax_return(self::HTTP_STATUS_FAIL,'修改文章失败');
            }

            // 更新relationship
            $relationship_obj_arr = array();

            // 默认填充到未分类目录中
            $categorys = $this->input->post('categorys') ?: array(0=>1);
            foreach ( $categorys as $c )
            {
                $rela = new \Beans\Relationship();
                $rela->object_id   = $post->ID;
                $rela->relation_id = intval($c);
                $rela->type        = 'category';

                array_push($relationship_obj_arr,$rela);
            }

            $tags = $this->input->post('tags');
            if ( $tags && is_array($tags) )
            {
                foreach ( $tags as $t )
                {
                    $rela = new \Beans\Relationship();
                    $rela->object_id   = $post->ID;
                    $rela->relation_id = intval($t);
                    $rela->type        = 'tag';

                    array_push($relationship_obj_arr,$rela);
                }
            }

            $this->load->model('relationships_model','relationships');

            // 在更新之前，删除与该文章相关的所有relationship
            $result = $this->relationships->delete_relationship(array(
                                                                array(
                                                                    'key'   =>'object_id',
                                                                    'value' =>$post->ID,
                                                                    'method'=>'where'
                                                                )
                                                                ));

            if ( !$result || FALSE === $this->relationships->insert_relationship($relationship_obj_arr) )
            {
                // 更新relationship失败的时候，文章也将被删除
                $this->posts->delete_post($post->ID);
                ajax_return(self::HTTP_STATUS_FAIL,'更新relationship失败');
            }

            // execute successful
            ajax_return(self::HTTP_STATUS_SUCCESS,'执行成功');
        }
        else
        {
            $ID = $this->input->get('id',FALSE);
            !$ID && show_404('访问内容不存在');

            $ID = hashids_decode($ID);
            $this->load->model('posts_model','posts');
            $data['post'] = $this->posts->get_post($ID);
            if ( !$data['post'] )
            {
                show_404('访问内容不存在');
            }

            // show new post page
            $this->load->model('categorys_model','categorys');
            $data['category_arr'] = $this->categorys->handler()->get_category();

            $this->load->model('tags_model','tags');
            $data['tag_arr'] = $this->tags->get_tags();

            $this->load->view('post/edit',$data);
        }
    }
}